package com.example.onlinereadingsystem.demos.web.util;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtTokenUtil {
    private static final String secret = "OSJA8*&af^AD$7ASFA14";
    //创建一个jwt密钥 加密和解密都需要用这个玩意
    private static final SecretKey key = Jwts.SIG.HS256.key()
            .random(new SecureRandom(secret.getBytes(StandardCharsets.UTF_8)))
            .build();

    //生成jwt令牌
    public static String generateJwt(Map<String, Object> claims) {
        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + 360000 * 1000))
                .compact();
        log.info("jwt-token: " + jwt);
        return jwt;
    }

    public static String createToken(Map<String, Object> claims) {
        JwtBuilder builder = Jwts.builder();
        Date now = new Date();
        // 生成token
        builder.claims(claims) //数据
                //.subject(username) //主题
                .issuedAt(now) //签发时间
                .expiration(new Date(System.currentTimeMillis() + 360000 * 1000)) //过期时间
                .signWith(key); //签名方式
        builder.header().add("JWT", secret);
        return builder.compact();
    }

    //解析jwt令牌
    public static Claims parseJwt(String token) throws JwtException {
        return Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();
    }

}
